<template>
  <view class="shop-container">
    <!-- 头部 -->
    <view class="header">
      <view class="balance-info">
        <text class="balance-label">账户余额</text>
        <text class="balance-amount">¥{{ userBalance.toFixed(2) }}</text>
      </view>
      <view class="shop-stats">
        <text class="stats-text">共{{ totalItems }}件商品</text>
      </view>
    </view>

    <!-- 分类导航 -->
    <view class="category-nav">
      <scroll-view scroll-x="true" class="nav-scroll">
        <view class="nav-items">
          <view 
            v-for="category in categories" 
            :key="category.value"
            class="nav-item"
            :class="{ active: selectedCategory === category.value }"
            @click="selectCategory(category.value)"
          >
            <text class="nav-text">{{ category.label }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-box">
        <input 
          v-model="searchKeyword"
          type="text"
          placeholder="搜索商品..."
          class="search-input"
          @input="handleSearch"
        />
        <text class="search-icon">🔍</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="items-section">
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="filteredItems.length === 0" class="empty-container">
        <text class="empty-text">暂无商品</text>
      </view>
      
      <view v-else class="items-grid">
        <view 
          v-for="item in filteredItems" 
          :key="item.id"
          class="item-card"
          @click="showItemDetail(item)"
        >
          <view class="item-image-container">
            <image 
              :src="item.imageUrl || '/static/images/default-item.png'" 
              class="item-image"
              mode="aspectFill"
            />
            <view v-if="item.isLimited" class="limited-badge">
              <text class="badge-text">限量</text>
            </view>
            <view v-if="item.rarity" class="rarity-badge" :class="getRarityClass(item.rarity)">
              <text class="rarity-text">{{ getRarityText(item.rarity) }}</text>
            </view>
          </view>
          
          <view class="item-info">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-description">{{ item.description }}</text>
            
            <view class="item-price-section">
              <view class="price-info">
                <text class="current-price">¥{{ item.price }}</text>
                <text v-if="item.originalPrice && item.originalPrice > item.price" class="original-price">
                  ¥{{ item.originalPrice }}
                </text>
              </view>
              
              <view class="item-actions">
                <button 
                  v-if="!userOwnsItem(item.id)"
                  class="buy-button"
                  :class="{ disabled: userBalance < item.price }"
                  :disabled="userBalance < item.price"
                  @click.stop="handlePurchase(item)"
                >
                  <text class="buy-text">购买</text>
                </button>
                <view v-else class="owned-badge">
                  <text class="owned-text">已拥有</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品详情弹窗 -->
    <view v-if="showDetailModal" class="detail-modal" @click="closeDetailModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ selectedItem.name }}</text>
          <text class="close-btn" @click="closeDetailModal">×</text>
        </view>
        
        <view class="modal-body">
          <image 
            :src="selectedItem.imageUrl || '/static/images/default-item.png'" 
            class="detail-image"
            mode="aspectFit"
          />
          
          <view class="detail-info">
            <text class="detail-description">{{ selectedItem.description }}</text>
            
            <view class="detail-price">
              <text class="detail-current-price">¥{{ selectedItem.price }}</text>
              <text v-if="selectedItem.originalPrice && selectedItem.originalPrice > selectedItem.price" class="detail-original-price">
                原价：¥{{ selectedItem.originalPrice }}
              </text>
            </view>
            
            <view class="detail-meta">
              <view class="meta-item">
                <text class="meta-label">类型：</text>
                <text class="meta-value">{{ getItemTypeName(selectedItem.itemType) }}</text>
              </view>
              <view class="meta-item">
                <text class="meta-label">稀有度：</text>
                <text class="meta-value">{{ getRarityText(selectedItem.rarity) }}</text>
              </view>
              <view v-if="selectedItem.isLimited" class="meta-item">
                <text class="meta-label">库存：</text>
                <text class="meta-value">{{ selectedItem.limitedQuantity - selectedItem.soldQuantity }}件</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button 
            v-if="!userOwnsItem(selectedItem.id)"
            class="purchase-button"
            :class="{ disabled: userBalance < selectedItem.price }"
            :disabled="userBalance < selectedItem.price"
            @click="handlePurchase(selectedItem)"
          >
            <text class="purchase-text">立即购买 ¥{{ selectedItem.price }}</text>
          </button>
          <view v-else class="owned-status">
            <text class="owned-status-text">您已拥有此商品</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 购买确认弹窗 -->
    <view v-if="showPurchaseModal" class="purchase-modal" @click="closePurchaseModal">
      <view class="purchase-content" @click.stop>
        <view class="purchase-header">
          <text class="purchase-title">确认购买</text>
        </view>
        
        <view class="purchase-body">
          <view class="purchase-item">
            <image :src="purchaseItem.imageUrl || '/static/images/default-item.png'" class="purchase-image" />
            <view class="purchase-info">
              <text class="purchase-name">{{ purchaseItem.name }}</text>
              <text class="purchase-price">¥{{ purchaseItem.price }}</text>
            </view>
          </view>
          
          <view class="balance-check">
            <text class="balance-label">当前余额：¥{{ userBalance.toFixed(2) }}</text>
            <text class="balance-after">购买后余额：¥{{ (userBalance - purchaseItem.price).toFixed(2) }}</text>
          </view>
        </view>
        
        <view class="purchase-footer">
          <button class="cancel-button" @click="closePurchaseModal">
            <text class="cancel-text">取消</text>
          </button>
          <button 
            class="confirm-button"
            :class="{ disabled: userBalance < purchaseItem.price }"
            :disabled="userBalance < purchaseItem.price"
            @click="confirmPurchase"
          >
            <text class="confirm-text">确认购买</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 加载提示 -->
    <view v-if="purchasing" class="loading-overlay">
      <view class="loading-content">
        <text class="loading-text">购买中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { NETWORK_CONFIG } from '@/config/network.js'

export default {
  name: 'ShopPage',
  data() {
    return {
      userId: null,
      userBalance: 0,
      totalItems: 0,
      selectedCategory: 'ALL',
      searchKeyword: '',
      shopItems: [],
      userOwnedItems: [],
      loading: false,
      purchasing: false,
      showDetailModal: false,
      showPurchaseModal: false,
      selectedItem: null,
      purchaseItem: null,
      categories: [
        { label: '全部', value: 'ALL' },
        { label: '主题', value: 'THEME' },
        { label: '头像框', value: 'AVATAR_FRAME' },
        { label: '聊天气泡', value: 'CHAT_BUBBLE' },
        { label: '铭牌', value: 'BADGE' },
        { label: '宠物', value: 'PET' },
        { label: '吉祥物', value: 'MASCOT' },
        { label: '个人名片', value: 'PERSONAL_CARD' },
        { label: '企业名片', value: 'ENTERPRISE_CARD' }
      ]
    }
  },
  computed: {
    filteredItems() {
      let items = this.shopItems
      
      // 按分类筛选
      if (this.selectedCategory !== 'ALL') {
        items = items.filter(item => item.itemType === this.selectedCategory)
      }
      
      // 按关键词搜索
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        items = items.filter(item => 
          item.name.toLowerCase().includes(keyword) || 
          item.description.toLowerCase().includes(keyword)
        )
      }
      
      return items
    }
  },
  onLoad(options) {
    this.userId = options.userId || 1 // 默认用户ID，实际应该从登录状态获取
    this.loadUserBalance()
    this.loadShopItems()
    this.loadUserOwnedItems()
  },
  methods: {
    // 加载用户余额
    async loadUserBalance() {
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/recharge/account`,
          method: 'GET',
          data: { userId: this.userId },
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          this.userBalance = parseFloat(response.data.data.balance) || 0
        }
      } catch (error) {
        console.error('加载用户余额失败:', error)
      }
    },
    
    // 加载商店商品
    async loadShopItems() {
      this.loading = true
      try {
        // 获取所有装饰类型
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/decoration/types`,
          method: 'GET'
        })
        
        if (response.data.success) {
          const decorations = response.data.data || {}
          this.shopItems = []
          
          // 合并所有装饰类型到商品列表
          Object.keys(decorations).forEach(type => {
            const items = decorations[type] || []
            items.forEach(item => {
              this.shopItems.push({
                id: item.id,
                name: item.name,
                description: item.description,
                price: item.price || 0,
                imageUrl: item.preview_image_url,
                itemType: item.decoration_type?.toUpperCase() || type.toUpperCase(),
                rarity: item.price > 0 ? 'RARE' : 'COMMON',
                isLimited: false,
                sponsorTable: item.sponsor_table,
                sponsorItemId: item.id
              })
            })
          })
          
          this.totalItems = this.shopItems.length
        }
      } catch (error) {
        console.error('加载商店商品失败:', error)
        uni.showToast({
          title: '加载商品失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载用户已拥有的商品
    async loadUserOwnedItems() {
      try {
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/decoration/owned/${this.userId}`,
          method: 'GET'
        })
        
        if (response.data.success) {
          this.userOwnedItems = response.data.data || []
        }
      } catch (error) {
        console.error('加载用户商品失败:', error)
      }
    },
    
    // 选择分类
    selectCategory(category) {
      this.selectedCategory = category
    },
    
    // 处理搜索
    handleSearch() {
      // 搜索逻辑在computed中处理
    },
    
    // 显示商品详情
    showItemDetail(item) {
      this.selectedItem = item
      this.showDetailModal = true
    },
    
    // 关闭详情弹窗
    closeDetailModal() {
      this.showDetailModal = false
      this.selectedItem = null
    },
    
    // 处理购买
    handlePurchase(item) {
      this.purchaseItem = item
      this.showPurchaseModal = true
    },
    
    // 关闭购买弹窗
    closePurchaseModal() {
      this.showPurchaseModal = false
      this.purchaseItem = null
    },
    
    // 确认购买
    async confirmPurchase() {
      if (!this.purchaseItem || this.userBalance < this.purchaseItem.price) {
        return
      }
      
      this.purchasing = true
      
      try {
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/decoration/purchase`,
          method: 'POST',
          data: {
            userId: this.userId,
            decorationType: this.purchaseItem.itemType.toLowerCase(),
            sponsorItemId: this.purchaseItem.sponsorItemId
          }
        })
        
        if (response.data.success) {
          uni.showToast({
            title: '购买成功',
            icon: 'success'
          })
          
          // 更新余额
          this.userBalance = parseFloat(response.data.newBalance)
          
          // 添加到已拥有商品
          this.userOwnedItems.push(this.purchaseItem)
          
          // 关闭弹窗
          this.closePurchaseModal()
          this.closeDetailModal()
        } else {
          uni.showToast({
            title: response.data.message || '购买失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('购买失败:', error)
        uni.showToast({
          title: '购买失败',
          icon: 'none'
        })
      } finally {
        this.purchasing = false
      }
    },
    
    // 检查用户是否拥有商品
    userOwnsItem(itemId) {
      return this.userOwnedItems.some(item => item.sponsor_item_id === itemId)
    },
    
    // 获取商品类型名称
    getItemTypeName(type) {
      const typeMap = {
        'THEME': '主题',
        'AVATAR_FRAME': '头像框',
        'CHAT_BUBBLE': '聊天气泡',
        'BADGE': '铭牌',
        'PET': '宠物',
        'MASCOT': '吉祥物',
        'PERSONAL_CARD': '个人名片',
        'ENTERPRISE_CARD': '企业名片'
      }
      return typeMap[type] || type
    },
    
    // 获取稀有度文本
    getRarityText(rarity) {
      const rarityMap = {
        'COMMON': '普通',
        'RARE': '稀有',
        'EPIC': '史诗',
        'LEGENDARY': '传说'
      }
      return rarityMap[rarity] || rarity
    },
    
    // 获取稀有度样式类
    getRarityClass(rarity) {
      const classMap = {
        'COMMON': 'rarity-common',
        'RARE': 'rarity-rare',
        'EPIC': 'rarity-epic',
        'LEGENDARY': 'rarity-legendary'
      }
      return classMap[rarity] || ''
    }
  }
}
</script>

<style scoped>
.shop-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  color: white;
}

.balance-info {
  text-align: center;
  margin-bottom: 20rpx;
}

.balance-label {
  display: block;
  font-size: 28rpx;
  opacity: 0.9;
  margin-bottom: 10rpx;
}

.balance-amount {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
}

.shop-stats {
  text-align: center;
}

.stats-text {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 分类导航样式 */
.category-nav {
  background: white;
  border-radius: 20rpx;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.nav-scroll {
  white-space: nowrap;
}

.nav-items {
  display: flex;
  padding: 0 20rpx;
}

.nav-item {
  padding: 15rpx 25rpx;
  margin-right: 15rpx;
  background: #f8f9fa;
  border-radius: 25rpx;
  transition: all 0.3s ease;
}

.nav-item.active {
  background: #667eea;
  color: white;
}

.nav-text {
  font-size: 26rpx;
  white-space: nowrap;
}

/* 搜索栏样式 */
.search-section {
  margin-bottom: 20rpx;
}

.search-box {
  position: relative;
  background: white;
  border-radius: 25rpx;
  padding: 0 20rpx;
}

.search-input {
  width: 100%;
  height: 80rpx;
  font-size: 28rpx;
  padding-right: 60rpx;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32rpx;
  color: #999;
}

/* 商品列表样式 */
.items-section {
  background: white;
  border-radius: 20rpx;
  padding: 20rpx;
}

.loading-container, .empty-container {
  text-align: center;
  padding: 60rpx 0;
}

.loading-text, .empty-text {
  color: #999;
  font-size: 28rpx;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.item-card {
  background: #f8f9fa;
  border-radius: 15rpx;
  overflow: hidden;
  transition: all 0.3s ease;
}

.item-card:active {
  transform: scale(0.98);
}

.item-image-container {
  position: relative;
  height: 200rpx;
}

.item-image {
  width: 100%;
  height: 100%;
}

.limited-badge {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background: #ff6b6b;
  color: white;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
}

.rarity-badge {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
}

.rarity-common {
  background: #95a5a6;
  color: white;
}

.rarity-rare {
  background: #3498db;
  color: white;
}

.rarity-epic {
  background: #9b59b6;
  color: white;
}

.rarity-legendary {
  background: #f39c12;
  color: white;
}

.item-info {
  padding: 20rpx;
}

.item-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-description {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 15rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info {
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #e74c3c;
  margin-right: 10rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.item-actions {
  display: flex;
  align-items: center;
}

.buy-button {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

.buy-button.disabled {
  background: #ccc;
  color: #999;
}

.owned-badge {
  background: #27ae60;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

/* 详情弹窗样式 */
.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  width: 90%;
  max-height: 80%;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.detail-image {
  width: 100%;
  height: 300rpx;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
}

.detail-info {
  margin-bottom: 20rpx;
}

.detail-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 20rpx;
}

.detail-price {
  margin-bottom: 20rpx;
}

.detail-current-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #e74c3c;
  margin-right: 15rpx;
}

.detail-original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
}

.detail-meta {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 10rpx;
}

.meta-value {
  font-size: 26rpx;
  color: #333;
}

.modal-footer {
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.purchase-button {
  width: 100%;
  height: 80rpx;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
}

.purchase-button.disabled {
  background: #ccc;
  color: #999;
}

.owned-status {
  text-align: center;
  padding: 20rpx;
}

.owned-status-text {
  color: #27ae60;
  font-size: 28rpx;
}

/* 购买确认弹窗样式 */
.purchase-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.purchase-content {
  background: white;
  border-radius: 20rpx;
  width: 90%;
  max-width: 500rpx;
}

.purchase-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.purchase-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.purchase-body {
  padding: 30rpx;
}

.purchase-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.purchase-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 15rpx;
  margin-right: 20rpx;
}

.purchase-info {
  flex: 1;
}

.purchase-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.purchase-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #e74c3c;
}

.balance-check {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 15rpx;
}

.balance-label {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.balance-after {
  font-size: 28rpx;
  color: #333;
}

.purchase-footer {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.cancel-button, .confirm-button {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.cancel-button {
  background: #f8f9fa;
  color: #666;
}

.confirm-button {
  background: #667eea;
  color: white;
}

.confirm-button.disabled {
  background: #ccc;
  color: #999;
}

/* 加载样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10001;
}

.loading-content {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #333;
}
</style>
